<template>
  <div class="uni-area-map">
    <el-dialog :title="title" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="visible">
      <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
        :disabled="method==='view'" label-width="120px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="名称" prop="name" :rules="[
                  {required: true, message:'名称不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父级编号" prop="parent.id" :rules="[

            ]">
              <SelectTree ref="parent" :props="{
                            value: 'id',             // ID字段名
                            label: 'name',         // 显示名称
                            children: 'childNodes'    // 子级字段名
                          }" v-if="visible" :url="`/lora/area/jfLoraArea/treeData?extId=${inputForm.id}`"
                :value="inputForm.parent.id" :clearable="true" :accordion="true"
                @getValue="(value) => {inputForm.parent.id=value}" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId" :rules="[
                {required: true, message:'楼层不能为空', trigger:'blur'}
               ]">
              <SelectTree ref="floor" placeholder="请选择楼层" :props="{
                  value: 'id',             // ID字段名
                  label: 'showName',         // 显示名称
                  children: 'childNodes'    // 子级字段名
                }" url="/smis/floor/jfFloor/treeData" :value="inputForm.floorId" :clearable="true" :accordion="true"
                @getValue="floorChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort" :rules="[
                  {required: true, message:'排序不能为空', trigger:'blur'},
                  {validator: validator.isNumber, trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.sort" placeholder="请填写排序"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="height: 400px;">
            <el-form-item label="区域绘制" prop="points" :rules="[
                  {required: true, message:'请绘制区域', trigger:'blur'}
                 ]">
              <FenceMap ref="fenceMap"></FenceMap>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="围栏" prop="points" :rules="[
                  {required: true, message:'围栏不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.points" placeholder="请填写围栏"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import FenceMap from '@/components/jfMap/fenceMap.vue'
  export default {
    data() {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          id: '',
          name: '',
          sort: '',
          floorId: '',
          points: '',
          parent: {
            id: ''
          }
        }
      }
    },
    components: {
      SelectTree,
      FenceMap
    },
    methods: {
      init(method, obj) {
        this.method = method
        this.inputForm.id = obj.id
        if (method === 'add') {
          this.title = '新建区域'
        } else if (method === 'addChild') {
          this.title = '添加下级区域'
        } else if (method === 'edit') {
          this.title = '修改区域'
        } else if (method === 'view') {
          this.title = '查看区域'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.inputForm.parent.id = obj.parent.id
          this.inputForm.parent.name = obj.parent.name
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/lora/area/jfLoraArea/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({
              data
            }) => {
              this.inputForm = this.recover(this.inputForm, data.jfLoraArea)
              this.loading = false
              if(this.$refs.fenceMap) {
                this.$refs.fenceMap.showFloor(this.inputForm.floorId)
                this.$refs.fenceMap.setDrawJson(this.inputForm.points)
              }
            })
          } else {
            if(this.$refs.fenceMap) {
              this.$refs.fenceMap.clearDraw()
            }
          }
          if(this.$refs.fenceMap) {
            this.$refs.fenceMap.resize();
          }
        })
      },
      // 表单提交
      doSubmit() {
				this.inputForm.points = JSON.stringify(this.$refs.fenceMap.getDrawJson());
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/lora/area/jfLoraArea/save`,
              method: 'post',
              data: this.inputForm
            }).then(({
              data
            }) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      },
      floorChange(value) {
        if (value && value != '') {
          this.inputForm.floorId = value;
          this.$refs.fenceMap.showFloor(value);
        }
      },
      /**
       * 检测目标点是否进入电子围栏区域
       * @param {Array} checkPoint - 校验坐标
       * @param {Array} polygonPoints - 形成电子围栏的坐标
       * @returns {Boolean} true 或 false
       * @description 此方法仅判断处于同一个平面的目标点是否在区域内（只判断坐标x和z值），
       *     不考虑两者当前离地高度（坐标的y值）
       */
      isInPolygon(checkPoint, polygonPoints) {
        var counter = 0;
        var i;
        var xinters;
        var p1, p2;
        var pointCount = polygonPoints.length;
        p1 = polygonPoints[0];
        for (i = 1; i <= pointCount; i++) {
          p2 = polygonPoints[i % pointCount];
          if (checkPoint.x > Math.min(p1.x, p2.x) && checkPoint.x <= Math.max(p1.x, p2.x)) {
            if (checkPoint.y <= Math.max(p1.y, p2.y)) {
              if (p1.x != p2.x) {
                xinters = (checkPoint.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
                if (p1.y == p2.y || checkPoint.y <= xinters) {
                  counter++;
                }
              }
            }
          }
          p1 = p2;
        }
        if (counter % 2 == 0) {
          return false;
        } else {
          return true;
        }
      }
    }
  }
</script>

<style lang="less">
  .uni-area-map {
    .el-dialog__body {
      height: 100%;
      position: relative;
      overflow: hidden;
    }

    // .el-dialog__footer {
    //   padding: 0;
    //   border-top: none;
    //   border-radius: 0;
    // }
  }
</style>
